// 引入路由组件
import VueRouter from 'vue-router';

//引入vue
import Vue from 'vue';
import routes from './routes'
import {getToken,deleteToken} from '@/utils/auth'
import store from '@/store'


//应用插件
Vue.use(VueRouter);

//将push,replase缓存
const originPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace
//修改VueRouter原型上的push，用于解决重复跳转报错
VueRouter.prototype.push = function(location,okCallback,errCallback){
    if(okCallback === undefined && errCallback === undefined){
        return originPush.call(this,location).catch(()=>{})
    }else{
        return originPush.call(this,location,okCallback,errCallback)
    }
}
//修改VueRouter原型上的replace，用于解决重复跳转报错
VueRouter.prototype.replace = function(location,okCallBack,errCallBack){
	if(okCallBack === undefined && error === errCallBack){
		return originalReplace.call(this,location).catch(()=>{})
	}else{
		return originalReplace.call(this,location,okCallBack,errCallBack)
	}
}

//创建路由器
const router = new VueRouter({
    mode:'history',
    routes,
    // scrollBehavior函数,每次路由跳转的时候都会执行
    //to 要跳到哪个路由 from 来自于哪个路由
    //savedPosition 跳转前滚动条的位置
    scrollBehavior(to , from , savedPosition){
        if(savedPosition){
            return savedPosition
        }
        return {x:0,y:0}
    }
})

router.beforeEach(async (to,from,next) => {
    //从local中获取token
    const token = getToken()
    //从vuex中获取userInfo
    const userInfo = store.state.user.userInfo
    //判断是否登录
    if (token) {
        console.log('登录了,有token,不确定vuex中的信息')
        //判断是否有用户信息
        if (userInfo.id) {
            console.log('有信息,直接过')
            next()
        }else{
            console.log('没信息,我去获取')
            try {
                await store.dispatch('getUserInfo')
                console.log('存入vuex')
                next()
            } catch (error) {
                console.log('失败了')
                //清除原有的token
                deleteToken()
                // 跳转到login
                next('/login')
            }
        }
    }else{
        console.log('没登录')
        next()
    }
})


export default router